/**
 * 
 */
package org.ephone;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import android.app.IntentService;
import android.content.Intent;
import android.inputmethodservice.InputMethodService;
import android.widget.Toast;
import android.app.Activity;
import android.app.Instrumentation;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Handler;
import android.os.Looper;
import android.view.WindowManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.util.Log;

/**
 * @author grudge
 *
 */
public class Commander extends IntentService {
    Handler handler;
    ePhoneApp appCommand;
    Toast test;
    
	public Commander (){
		super("Commander");
	}
	
	
	@Override
	protected void onHandleIntent(Intent intent) {
		appCommand = (ePhoneApp)getApplicationContext();
		Socket s = null;
        int code, status;
        char[] buff = new char[4];
        
        try {
        	while (s == null) {
        		s = new Socket("127.0.0.1", 12345);
        		Thread.sleep(10000);
        	}
        	InputStream is = s.getInputStream();
        	InputStreamReader isReader = new InputStreamReader(is);
            BufferedReader isFromDriver = new BufferedReader(isReader);
            while(true){
                // read the code
                status = isFromDriver.read(buff);
                if (status < 0) return;
               
                appCommand.setCommand(new String (buff));
                //code = Integer.valueOf(buff[0]);

            }
        } catch (Exception ee){
        	test = Toast.makeText(getApplicationContext(), ee.toString(), Toast.LENGTH_LONG);
        	//test.show();
        }
        /*
		while (true){
			//ASCOLTA LA CONNESSIONE SOCKET
	        try {
	        	// INVIA IL MESSAGGIO RICEVUTO DAL SOCKET
	        	appCommand.setCommand("00");
	        	Thread.sleep(10000);
	        } catch (Exception ee){
	        	test = Toast.makeText(getApplicationContext(), ee.toString(), Toast.LENGTH_LONG);
	        	test.show();
	        }
		}
		*/
	}
}
